<?php

namespace app\admin\model;

use think\Model;
use think\Session;
use think\Validate;

class Admin extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 重置用户密码
     * @author baiyouwen
     */
    public function resetPassword($uid, $NewPassword)
    {
        $passwd = $this->encryptPassword($NewPassword);
        $ret = $this->where(['id' => $uid])->update(['password' => $passwd]);
        return $ret;
    }

    // 密码加密
    protected function encryptPassword($password, $salt = '', $encrypt = 'md5')
    {
        return $encrypt($password . $salt);
    }

    /**
     * @param $username
     * @param $password
     * @return bool when user is valid return user, invalid return 0
     * @throws \think\exception\DbException
     */
    public static function isValid($username, $password)
    {
        $rule = [
            'username'  => 'require|length:3,30',
            'password'  => 'require|length:3,30',
        ];
        $data = [
            'username'  => $username,
            'password'  => $password,
        ];
        $validate = new Validate($rule);

        if(! $validate->check($data)) return false;

        $user = self::get(['username' => $username]);
        if (!$user){
            return 0;
        }
        if ($user->password != md5(md5($password) . $user->salt))
        {
            return 0;
        }
        return $user;
    }
	
	public function orgnazation()
	{
		return $this->belongsTo('Orgnazation','orgid');
	}

    /**
     * 验证用户是否属于用户组
     * @param $username 用户名
     * @param $groupname 组名
     * @return bool
     * @throws \think\exception\DbException
     */
    public static function isGroup($username,$groupname)
    {
        $user = self::get(['username' => $username]);
        if (!$user){
            return false;
        }
        $group = AuthGroup::get(['name'=>$groupname]);
        if(!$group){
            return false;
        }
        else{
            $inGroup = AuthGroupAccess::get(['uid'=>$user->id,'group_id'=>$group->id]);
            if(!$inGroup) return false;
            else          return true;
        }
    }

}
